package org.lop.modules.web.struts2;

import org.lop.common.domain.BaseEntity;
import org.lop.modules.data.domain.PageableBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

/**
 * Struts2抽象模版基类.
 * 
 * @author 潘瑞峥
 * @date 2013-6-3
 */
public abstract class CrudActionSupport<T extends BaseEntity, PK> extends ActionSupport implements ModelDriven<T>, Preparable {

	private static final long serialVersionUID = -5252359775960706004L;

	protected Logger logger = LoggerFactory.getLogger( this.getClass() );

	/** 进行增删改操作后, 以redirect方式重新打开action默认页的result名. */
	public static final String RELOAD = "reload";

	/** entity. */
	protected T entity;

	/** id. */
	protected PK id;

	/** page. */
	protected PageableBean pageable;

	/** 对象版本号, 配合@Version防止并发修改. */
	protected Integer workingVersion;

	@Override
	public T getModel() {
		return entity;
	}

	public void setId( PK id ) {
		this.id = id;
	}

	public PageableBean getPageable() {
		return pageable;
	}

	public void setPageable( PageableBean pageable ) {
		this.pageable = pageable;
	}

	public void setWorkingVersion( Integer workingVersion ) {
		this.workingVersion = workingVersion;
	}

	/**
	 * Action函数, 默认的action函数, 默认调用list()函数.
	 */
	@Override
	public String execute() throws Exception {
		return json();
	}

	/**
	 * 实现空的prepare()函数, 屏蔽所有Action函数公共的二次绑定.
	 */
	@Override
	public void prepare() throws Exception {
	}

	/**
	 * 在input()前执行二次绑定.
	 */
	public void prepareInput() throws Exception {
		prepareModel();
	}

	/**
	 * 在save()前执行二次绑定.
	 */
	public void prepareSave() throws Exception {
		prepareModel();
	}

	/**
	 * 等同于prepare()的内部函数, 供prepardMethodName()函数调用.
	 */
	protected abstract void prepareModel() throws Exception;

	/**
	 * Json列表.
	 * 
	 * 建议return null.
	 */
	public abstract String json() throws Exception;

	/**
	 * List列表.
	 * 
	 * 建议return SUCCESS.
	 */
	public abstract String list() throws Exception;

	/**
	 * 新增或修改界面.
	 * 
	 * 建议return INPUT.
	 */
	@Override
	public abstract String input() throws Exception;

	/**
	 * 新增或修改.
	 * 
	 * 建议return RELOAD.
	 */
	public abstract String save() throws Exception;

	/**
	 * 删除.
	 * 
	 * 建议return RELOAD.
	 */
	public abstract String delete() throws Exception;

}